<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use app\common\model\UserScoreLog;
use think\Controller;
use think\Db;
use think\Request;


class Wanlshoporder extends Api
{
    private static $model;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = model('app\api\model\wanlshop\Order');
    }

    /**
     * 创建订单
     */
    public function create()
    {
        $orderNum = input('order_num');
        if (!$orderNum) {
            $this->error('参数缺失！');
        }

        $orderInfo = self::$model->where('order_no', $orderNum)->find();
        if ($orderInfo) {
            if ($orderInfo->state != 1) {
                $this->error('该订单不可支付！');
            }
        }

        $lists = \app\common\model\WanlshopOrderGoods::field('id,shop_name,shop_id,title,image,difference,price,number')->where('order_num', $orderNum)->order('id desc')->select();
        if (!$lists) {
            $this->error('商品清单为空！');
        }

        $catchtime = input('catchtime');
        if (!$catchtime) {
            $this->error('请选择自提时间！');
        }

        $total = 0.00;
        foreach ($lists as $val) {
            $total += $val->price * $val->number;
        }

        $userId = $this->auth->id;
        $user = \app\common\model\User::find($userId);
        if ($user->score < $total) {
            $this->error('积分余额不足！');
        }

//        $price = $listInfo->price;
//        $total = round($price * $nums, 2);
        $odata = [
            'user_id' => $userId,
            'order_no' => $orderNum,
//            'store_id' => $nums,
            'total' => $total,
//            'status' => 0,
        ];

        if ($orderInfo) {
            self::$model->where('id', $orderInfo->id)->update(['createtime' => time(), 'total' => $total]);
        } else {
            $ret = self::$model->create($odata);
            $orderId = $ret->id;
            \app\common\model\WanlshopOrderGoods::where('order_num', $orderNum)->update(['order_id' => $orderId]);
        }

        // 更新状态
        self::$model->update(['state' => 2, 'paymenttime' => time()]);

        // 支付订单
        $user->score -= $total;
        $user->save();

        // 财务流水
        $before = round($user->score + $total, 2);
        $sdata = [
            'user_id' => $userId,
            'record_type' => 0,
            'score' => $total,
            'before' => $before,
            'after' => $user->score,
            'memo' => '积分兑换，订单id为' . $orderId,
        ];
        UserScoreLog::create($sdata);

        Db::startTrans();
        try {


            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('订单创建失败！');
        }

        $this->success('订单创建成功！');
    }

    /**
     * 订单支付
     */
//    public function pay()
//    {
//        $userId = $this->auth->id;
//        $orderNum = input('order_num');
//        $row_info = self::$model->where('order_num', $orderNum)->find();
//        if (!$row_info) {
//            $this->error('参数错误！');
//        }
//        if ($row_info->status >= 1) {
//            $this->error('该订单已支付！');
//        }
//
//        $listInfo = \app\common\model\CompetitionLists::find($row_info->list_id);
//        if ($row_info->nums > $listInfo->num) {
//            $this->error('票数余量不足！');
//        }
//
//        $now = date('Y-m-d H:i:s', time());
//        if ($now > $listInfo->regist_end_time) {
//            $this->error('报名已结束！');
//        }
//
//        $type = input('type', 2);//1小程序，2微信公众号，3h5，4app
//        self::$model->where('id', $row_info->id)->update(['paytype' => $type]);
//        Db::startTrans();
//        try {
//            $openIdApp = \app\common\model\User::where('id', $userId)->value('open_id_app');
//            $openIdApplet = \app\common\model\User::where('id', $userId)->value('open_id_applet');
//
////            $odata = [
////                'body' => $goodsInfo->name,
////                'out_trade_no' => $row_info->order_num,
////                "money" => $row_info->total,
//////                        "money" => 0.01,
////            ];
////
////            if ($type == 2) {
////                $odata['openid'] = $user->open_id_wechat;
////            }
//////
////            $paymentObj = new Payment();
////            $res = $paymentObj->wx_pay($odata, $type);
//
////            $res = $paymentObj->handleOrder($row_info->order_num);
//            $third_config = include(APP_PATH . 'third.php');
//            $params = [
//                'amount' => $row_info->total,
//                'orderid' => $row_info->order_num,
//                'type' => "wechat",
//                'title' => '报名成功',
//                'notifyurl' => $third_config['notify_url'],
//                'method' => "miniapp",
//                'auth_code' => ""
//            ];
//
//            if ($type == 2) {
//                $params['method'] = 'mp';
////                $params['openid'] = $openIdWechat;
//            } elseif ($type == 1) {
//                $params['method'] = 'miniapp';
//                $params['openid'] = $openIdApplet;
//            } elseif ($type == 3) {
//                $params['method'] = 'app';
//                $params['openid'] = $openIdApp;
//            }
//
//            $res = Service::submitOrder($params);
//
//            // 提交事务
//            Db::commit();
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//
//        $this->success('支付成功！', $res);
//    }
}
